<template>
  <div>
    <el-dialog v-drag width="90%" height="100%" :fullscreen="false" v-drag @opened="initItemData()"
      :title="!dataForm.clearId ? '新增装斗清斗' : '修改装斗清斗'" :close-on-click-modal="false" :visible.sync="visible">
      <el-form :model="dataForm" :inline="true" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
        label-width="80px">
        <el-form-item label="单号" prop="clearNo">
          <el-input size="mini" v-model="dataForm.clearNo" disabled placeholder="单号" clearable></el-input>
        </el-form-item>
        <el-form-item label="日期" prop="clearDate">
          <el-date-picker size="mini" style="width:100%;" v-model="dataForm.clearDate" value-format="yyyy-MM-dd"
            type="date" clearable placeholder="日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核人" prop="auditor">
          <el-select size="mini" @focus="getUsers()" @change="setUsers()" v-model="dataForm.auditor" clearable
            placeholder="请选择">
            <el-option v-for="item in users" :key="item.userId" :label="item.username" :value="item.username">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="复核人" prop="checkName">
          <el-select size="mini" @focus="getUsers()" @change="setUsers()" v-model="dataForm.checkName" clearable
            placeholder="请选择">
            <el-option v-for="item in users" :key="item.userId" :label="item.username" :value="item.username">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input size="mini" type="textarea" :autosize="{minRows: 1, maxRows: 4}" v-model="dataForm.remark"
            placeholder="备注" clearable></el-input>
        </el-form-item>

        <!-- 子表 -->
        <el-divider></el-divider>
        <el-form-item>
          <el-button class="line-button" size="mini" circle type="primary" @click="addRow()"><span
              class="icon iconfont">&#xe664;</span></el-button>
         <el-button class="line-button" size="mini" circle type="danger" @click="deleteRows()"><span
              class="icon iconfont">&#xe813;</span></el-button>
        </el-form-item>
        <el-table :data="dataForm.itemList" border size="mini" class="item-table" height="250"
          @selection-change="selectionChangeHandle" ref="itemTable"
          :header-cell-style="{ background: '#fcfcfc', color: '#606266', height:'36px'}">
          <el-table-column type="selection" header-align="center" align="center" width="50">
          </el-table-column>
          <el-table-column type="index" header-align="center" align="center" width="40" label="#">
          </el-table-column>
          <el-table-column prop="productCode" header-align="center" width="150" align="center" label="药品编码">
            <template slot-scope="scope">
                <div class="product-code-box" v-if="scope.row.productCode == ''">
                  <el-form-item :prop="'itemList.'+scope.$index+'.productCode'" :rules="dataRule.productCode">
                    <el-input size="mini" v-model="scope.row.productCode" disabled class="product-code-input"
                      @blur='blurInput(scope.row, "productCode", scope.row.productCode)' v-focus>
                    </el-input>
                  </el-form-item>
                  <el-button size="mini" class="chose-button"  @click="selectproduct(scope.row)"><span
                      class="icon iconfont">&#xe68e;</span></el-button>
                </div>
              <span v-else>{{scope.row.productCode}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="productName" header-align="center" width="180" align="center" label="药品名称">
          </el-table-column>
          <el-table-column prop="beforeClearNum" header-align="center" width="130" align="center" label="清斗前数量">
          </el-table-column>
          <el-table-column prop="clearNum" header-align="center" width="130" align="center" label="清斗数量">
            <template slot-scope="scope">
              <el-form-item :prop="'itemList.'+scope.$index+'.clearNum'" :rules="dataRule.clearNum">
                <el-input size="mini" v-model="scope.row.clearNum"
                type="number" :min="1"  oninput="value=value.replace(/^0|[^0-9]/g, '')"
                  @blur='blurInput(scope.row, "clearNum", scope.row.clearNum)' v-focus> </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="clearDate" header-align="center" width="200" align="center" label="清斗时间">
            <template slot-scope="scope">
              <el-form-item :prop="'itemList.'+scope.$index+'.clearDate'" :rules="dataRule.clearDate">
                <el-date-picker size="mini" v-model="scope.row.clearDate" value-format="yyyy-MM-dd HH:mm:ss" style="width:100%;"
                  type="datetime" clearable placeholder="清斗时间"
                  @blur='blurInput(scope.row, "clearDate", scope.row.clearDate)'>
                </el-date-picker>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="putNum" header-align="center" width="130" align="center" label="装斗数量">
            <template slot-scope="scope">
              <el-form-item :prop="'itemList.'+scope.$index+'.putNum'" :rules="dataRule.putNum">
                <el-input size="mini" v-model="scope.row.putNum" type="number"
                  @blur='blurInput(scope.row, "putNum", scope.row.putNum)'>
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="putDate" header-align="center" width="200" align="center" label="装斗时间">
            <template slot-scope="scope">
              <el-form-item :prop="'itemList.'+scope.$index+'.putDate'" :rules="dataRule.putDate">
                <el-date-picker size="mini" v-model="scope.row.putDate" value-format="yyyy-MM-dd HH:mm:ss" style="width:100%;"
                  type="datetime" clearable placeholder="清斗时间"
                  @blur='blurInput(scope.row, "putDate", scope.row.putDate)'>
                </el-date-picker>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="clearBatchNo" header-align="center" width="120" align="center" label="清斗批号">
            <template slot-scope="scope">
              <el-form-item :prop="'itemList.'+scope.$index+'.clearBatchNo'" :rules="dataRule.clearBatchNo">
                <el-input size="mini" v-model="scope.row.clearBatchNo"
                  @blur='blurInput(scope.row, "clearBatchNo", scope.row.clearBatchNo)' v-focus>
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="bucketUser" header-align="center" width="150" align="center" label="装斗人">
            <template slot-scope="scope">
              <el-select size="mini" @focus="getUsers()"  v-model="scope.row.bucketUser" clearable
                @blur='blurInput(scope.row, "bucketUser", scope.row.bucketUser)'
                placeholder="请选择">
                <el-option v-for="item in users" :key="item.userId" :label="item.username" :value="item.username">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="clearUser" header-align="center" width="150" align="center" label="清斗人">
            <template slot-scope="scope">
              <el-select size="mini" @focus="getUsers()"  v-model="scope.row.clearUser" clearable
                @blur='blurInput(scope.row, "clearUser", scope.row.clearUser)'
                placeholder="请选择">
                <el-option v-for="item in users" :key="item.userId" :label="item.username" :value="item.username">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="qualityInfo" header-align="center" width="150" align="center" label="质量状况">
            <template slot-scope="scope">
              <el-input size="mini" v-model="scope.row.qualityInfo" type="textarea"
                @blur='blurInput(scope.row, "qualityInfo", scope.row.qualityInfo)' autosize>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="batchNo" header-align="center" width="120" align="center" label="批号">
          </el-table-column>
          <el-table-column prop="produceDate" header-align="center" width="140" align="center" label="生产日期">
          </el-table-column>
          <el-table-column prop="expiryDate" header-align="center" width="140" align="center" label="有效期">
          </el-table-column>
          <el-table-column prop="barCode" header-align="center" width="120" align="center" label="条码">
          </el-table-column>
          <el-table-column prop="genericName" header-align="center" width="180" align="center" label="通用名称">
          </el-table-column>
          <el-table-column prop="standard" header-align="center" width="140" align="center" label="规格">
          </el-table-column>
          <el-table-column prop="unit" header-align="center" align="center" label="单位">
          </el-table-column>
          <el-table-column prop="producingArea" header-align="center" width="180" align="center" label="产地">
          </el-table-column>
          <el-table-column prop="produceFactory" header-align="center" width="180" align="center" label="生产单位">
          </el-table-column>
          <el-table-column prop="approvalNo" header-align="center" width="140" align="center" label="批准文号">
          </el-table-column>
          <el-table-column prop="dosageForm" header-align="center" width="160" align="center" label="剂型">
          </el-table-column>

          <el-table-column prop="remark" header-align="center" width="150" align="center" label="备注">
            <template slot-scope="scope">
              <el-input size="mini" v-model="scope.row.remark" type="textarea"
                @blur='blurInput(scope.row, "remark", scope.row.remark)' autosize>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column fixed="right" align="center" label="操作" width="100">
            <template slot-scope="scope">
              <el-button size="mini" type="danger" icon="el-icon-minus" class="delete-button"
                @click.native.prevent="deleteRow(scope.$index)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="visible = false">取消</el-button>
        <el-button size="mini" type="primary" @click="dataFormSubmit()">保存</el-button>
      </span>
    </el-dialog>
    <!-- 弹窗, 新增 / 修改 -->
    <product-select v-if="productSelectVisible" ref="productSelectRef" @refreshDataList=""></product-select>
  </div>
</template>

<script>
  import cloneDeep from 'lodash/cloneDeep'
  import ProductSelect from '@/views/components/product-select.vue'
  export default {
    components: {
      ProductSelect
    },
    data() {
      var checkNum = (rule, value, callback) => {
        if (!value || value < 1) {
          return callback(new Error('数量不能<1'));
        } else {
          callback();
        }
      };
      var checkPrice = (rule, value, callback) => {
        if (!value || value < 0.01) {
          return callback(new Error('价格不能<0.01'));
        } else {
          callback();
        }
      };
      return {
        visible: false,
        productSelectVisible: false,
        dataForm: {
          clearId: undefined,
          clearNo: '',
          clearDate: this.getNowDate(),
          aduidtStatus: 0,
          auditor: '',
          auditorId: '',
          checkStatus: 0,
          checkName: '',
          checkId: '',
          remark: '',
          itemList: []
        },
        dataRule: {
          clearNo: [{
            required: true,
            message: '单号不能为空',
            trigger: 'blur'
          }],
          clearDate: [{
            required: true,
            message: '日期不能为空',
            trigger: 'blur'
          }],
          auditor: [{
            required: true,
            message: '审批人不能为空',
            trigger: 'blur'
          }],
          checkName: [{
            required: true,
            message: '复核人不能为空',
            trigger: 'blur'
          }],
          clearDate: [{
            required: true,
            message: '清斗时间不能为空',
            trigger: 'blur'
          }],
          putDate: [{
            required: true,
            message: '装斗时间不能为空',
            trigger: 'blur'
          }],
          clearNum: [{
            required: true,
            validator: checkNum,
            trigger: 'blur'
          }],
          putNum: [{
            required: true,
            validator: checkNum,
            trigger: 'blur'
          }],
        },
        oldData: {},
        showInput: "",
        dataListSelections: [],
        currentProduct: {},
        suppliers: [],
        users: [],
      }
    },
    watch: {
      currentProduct: {
        handler(obj, oldVal) {
          let product = {}
          product.productId = obj.productId;
          product.productCode = obj.productCode;
          product.productName = obj.productName;
          product.barCode = obj.barCode;
          product.genericName = obj.genericName;
          product.standard = obj.standard;
          product.unit = obj.unit;
          product.producingArea = obj.producingArea;
          product.produceFactory = obj.produceFactory;
          product.approvalNo = obj.approvalNo;
          product.dosageForm = obj.dosageForm;
          product.batchNo = obj.batchNo;
          product.produceDate = obj.produceDate;
          product.expiryDate = obj.expiryDate;
          product.beforeClearNum = obj.totalStorage;
          product.clearDate = null;
          product.putDate = null;
          product.clearNum = 0;
          product.putNum = 0;
          product.qualityInfo = '';
          product.clearBatchNo = '';
          product.rowNum = new Date().getTime()
          product.remark = '';
          let isAdd = false;
          let itemList = this.dataForm.itemList
          itemList.forEach((item, index) => {
            if (item.productCode === product.productCode || item.barCode === product.barCode) {
              isAdd = true;
              this.$message.error("[" + item.productCode + "]该药品已经添加！")
              return;
            }
            if (!item.productCode) {
              itemList.splice(index, 1)
            }
          })
          if (!isAdd) {
            itemList.push(product)
            this.dataForm.itemList = itemList
          }
          // this.addRow()
        },
        immediate: true
      }
    },
    methods: {
      initItemData() {
        // this.dataForm.itemList = []
        // this.addRow()
      },
      init(clearId) {
        this.dataForm.itemList = []
        this.dataForm.clearId = clearId
        this.visible = true
        this.$nextTick(async () => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.clearId) {
            const res = await this.$http({
              url: `/stock/stockbucketclear/info/${this.dataForm.clearId}`,
              method: 'get',
              params: this.$http.adornParams()
            })
            let data = res.data
            if (data && data.code === 0) {
              this.dataForm = data.purchaseOrder
            }
          } else {
            const res = await this.$http({
              url: `/stock/stockbucketclear/getOrderNo`,
              method: 'get',
              params: this.$http.adornParams()
            })
            let data = res.data
            if (data && data.code === 0) {
              this.dataForm.clearNo = data.data
              this.addRow()
            }
          }
        })
      },
      // 表单提交
      dataFormSubmit() {
        this.$refs['dataForm'].validate(async (valid) => {
          if (valid) {
            this.dataForm.itemList.forEach((item, index) => {
              item.status = 1
              if(!item.productCode || !item.barCode){
                this.dataForm.itemList.splice(index, 1)
              }
            })
            const res = await this.$http({
              url: `/stock/stockbucketclear/${!this.dataForm.clearId ? 'saveOrder' : 'updateOrder'}`,
              method: 'post',
              data: this.$http.adornData(this.dataForm)
            })
            let data = res.data
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          }
        })
      },
      blurInput(row, name, value) {
        // 判断数据是否有所改变，如果数据有改变则调用修改接口
        if (this.oldData[name] != value) {
          row[name] = value
          //this.saveHandle(row, `/stock/stockbucketclearitem/update`)
        }
        let totalFee = 0;
        this.dataForm.itemList.forEach((item, index) => {
          if (item.clearNum && item.putNum) {
            item.purchaseFee = Number(item.clearNum) * Number(item.putNum)
            totalFee += item.purchaseFee
          }
        })
        this.dataForm.totalFee = totalFee
        this.showInput = ""
      },
      addRow() {
        let item = {
          rowNum: new Date().getTime(),
          purchaseOrderDetaiId: undefined,
          clearId: '',
          clearNo: '',
          productId: '',
          productCode: '',
          genericName: '',
          standard: '',
          unit: '',
          producingArea: '',
          produceFactory: '',
          approvalNo: '',
          dosageForm: '',
          batchNo: '',
          produceDate: '',
          expiryDate: '',
          barCode: '',
          stockCount: '',
          clearNum: 0,
          putNum: 0,
          purchaseAmount: 0,
          lastPurchasePrice: 0,
          retailPrice: 0,
          newRetailPrice: 0,
          memberPrice: 0,
          newMemberPrice: 0,
          remark: ''
        }
        this.dataForm.itemList.push(item)
      },
      deleteRows() {
        this.dataListSelections.forEach((val, index) => {
          this.dataForm.itemList.forEach((v, i) => {
            if (val.rowNum === v.rowNum) {
              // i 为选中的索引
              this.dataForm.itemList.splice(i, 1)
            }
          })
        })
        // 删除完数据之后清除勾选框
        this.$refs.itemTable.clearSelection()
      },
      //第三：点击 — 号执行删除一行的方法
      deleteRow(index) {
        //利用数组的splice方法，将该index数据删除
        this.dataForm.itemList.splice(index, 1);
      },
      selectionChangeHandle(val) {
        this.dataListSelections = val
      },
      selectproduct(row) {
        this.productSelectVisible = true
        this.$nextTick(() => {
          this.$refs.productSelectRef.init()
        })
      },
      async getUsers() {
        const res = await this.$http({
          url: `/sys/user/listUsers`,
          method: 'get',
          params: this.$http.adornParams()
        })
        let data = res.data
        if (data && data.code === 0) {
          this.users = data.data
        }
      },
      setUsers() {
        this.users.forEach((item) => {
          if (this.dataForm.auditUser == item.username) {
            this.dataForm.auditUserId = item.userId;
          } else if (this.dataForm.purchaseUser == item.username) {
            this.dataForm.purchaseUserId = item.userId;
          }
        });
      },
      async getDicts(type) {
        const res = await this.$http({
          url: '/base/basedict/getDict',
          method: 'get',
          params: this.$http.adornParams({
            'code': type
          })
        })
        let data = res.data
        if (data && data.code === 0) {
          if (type === 'PAY_METHOD') {
            this.paymentMethods = data.data
          }
        }
      },
    },
    directives: {
      // 通过自定义指令实现的表单自动获得光标的操作
      focus: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "input") {
            el.focus()
          } else {
            if (el.getElementsByTagName("input")) {
              el.getElementsByTagName("input")[0].focus()
            }
          }
          el.focus()
        }
      },
      focusTextarea: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "textarea") {
            el.focus()
          } else {
            if (el.getElementsByTagName("textarea")) {
              el.getElementsByTagName("textarea")[0].focus()
            }
          }
          el.focus()
        }
      }
    }
  }
</script>
<style lang="less" scoped>
  .el-dialog__body {
    padding: 5px 20px 30px 20px;
  }

  .product-code-box {
    display: flex;
    justify-content: right;
    align-items: center;

    .product-code-input {
      background-color: #fff;

      .el-input__inner {
        border: 0px !important;
        background-color: #fff;
      }
    }
    .chose-button {
      margin: 0 0 10px 0;
      height: 30px;
      width: 18px;
      padding: 3px 1px;
      margin-left: 2px;
      background-color: #e4f3f7;
    }
  }

  .el-divider {
    margin-bottom: 5px;
  }

  .icon {
    margin-right: 0px;
  }

  .delete-button {
    padding: 3px 5px;
  }

  .el-textarea__inner {
    line-height: 1 !important;
  }
  .el-date-picker{
    width: 100%;
  }

  .el-date-editor.el-input, .el-date-editor.el-input__inner {
     width: auto;
  }

  .el-form-item__error{
    padding-top: 0px!important;
    z-index: 99;
  }

  .el-table{
    // .el-form-item {
    //   margin: 0px;
    //   padding: 0px;
    // }

  }



</style>
